package net.piggy.gateway;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;

public class HttpServer {

    private final static Logger logger = LoggerFactory.getLogger(HttpServer.class);

    public static void main(String[] args) throws InterruptedException, IOException {
        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup work = new NioEventLoopGroup(4);
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boss, work)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel channel) {
                        ChannelPipeline pipeline = channel.pipeline();
                        pipeline.addLast(new LoggingHandler(LogLevel.INFO));
                        pipeline.addLast(new HttpRequestDecoder());
                        pipeline.addLast(new HttpObjectAggregator(8192));
                        pipeline.addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                Channel channel = ctx.channel();
                                FullHttpRequest request = (FullHttpRequest) msg;
                                String uri1 = request.uri();
                                int idx = uri1.indexOf("?");
                                String uri2 = idx > 0 ? uri1.substring(0, idx) : uri1;
                                if (uri2.equals("/favicon.ico")){
                                    request.release();
                                    return;
                                } else {
                                    logger.info("request uri -> " + uri1);
                                }
                                String content = request.content().toString(CharsetUtil.UTF_8);
                                logger.info("request body -> " +content);
                                HttpClient.send(request, channel);
                                logger.info("request refCnt -> "+request.refCnt());
                            }
                        });
                        pipeline.addLast(new HttpResponseEncoder());
                    }
                });
        Channel channel = bootstrap.bind(Config.getConfigParam().getIp(), Config.getConfigParam().getPort()).sync().channel();
        ChannelFuture channelFuture = channel.closeFuture().sync();
        channelFuture.addListener((ChannelFutureListener) listener -> logger.info("server close"));
    }
}
